// pages/search/search.js
import { searchRecipes } from '../../api/search.js';
const app = getApp(); // 获取 app.js 的实例
Page({
  data: {
    value: '',
    hotWords: ['家常菜', '每日三餐', '外国食谱', '川菜', '湘菜', '粤菜', '早餐', '午餐', '晚餐'],
    historyWords: [],
    showModal: false,
    searchQuery: '',
    recipes: []
  },

  async onLoad() {
    await app.checkLoginStatus();
    // 从本地存储获取历史搜索记录
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      historyWords: history
    });
  },

  // 输入事件处理
  onInput(e) {
    const value = e.detail.value.trim();
    this.setData({ value: value });

    // 如果模态框开启且输入框内容为空，关闭模态框
    if (this.data.showModal && !value) {
      this.closeModal();
    }
  },

  // 搜索事件处理
  onSearch() {
    const value = this.data.value.trim();
    if (value) {
      this.saveSearchHistory(value);
      this.fetchSearchResults(value);
    }
  },
  // 调用后端接口获取食谱的搜索结果
  async fetchSearchResults(keyword) {
    const data = {
      keyword: keyword,
      current: 1,
      pageSize: 10
    };
    const res = await searchRecipes(data);
    if (res.success) {
      this.setData({
        searchQuery: keyword,
        recipes: res.data.records,
        showModal: true
      });
    }
  },

  // 点击热词搜索
  searchHotWord(e) {
    const word = e.currentTarget.dataset.word;
    this.setData({ value: word });
    this.saveSearchHistory(word);
    this.fetchSearchResults(word);
  },

  // 保存搜索历史
  saveSearchHistory(word) {
    let history = this.data.historyWords;
    // 移除重复项
    history = history.filter(item => item !== word);
    // 添加到开头
    history.unshift(word);
    // 限制数量
    if (history.length > 10) {
      history.pop();
    }
    this.setData({
      historyWords: history
    });
    wx.setStorageSync('searchHistory', history);
  },

  // 清空历史记录
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            historyWords: []
          });
          wx.removeStorageSync('searchHistory');
        }
      }
    });
  },

  closeModal() {
    this.setData({
      showModal: false,
      value: '', // 清空搜索词
      searchQuery: '',
      recipes: []
    });
  },

  // 取消搜索
  onCancel() {
    if (this.data.showModal) {
      this.closeModal();
    } else {
      wx.navigateBack();
    }
  },

  goToRecipeDetail(event) {
    const recipeId = event.currentTarget.dataset.recipeId;
    wx.navigateTo({
      url: `/pages/recipeDetail/recipeDetail?recipeId=${recipeId}`
    });
  }
});